package api

import (
	"bytes"
	"fmt"
	"html/template"
	"net/http"
	"path/filepath"

	"github.com/julienschmidt/httprouter"
	"learning.com/edu/utils/validator"
)

type templateData struct {
	BackgroundColor string
	ForegroundColor string
}

func (api *Api) pageProvider(w http.ResponseWriter, r *http.Request) {
	qs := r.URL.Query()
	key := api.h.ReadString(qs, "key", "")
	bg := api.h.ReadString(qs, "bg", "000000")
	fg := api.h.ReadString(qs, "fg", "ffffff")

	keyValues := []string{"userprotocol", "userprivacy", "usercancellation"}
	if !validator.PermittedValue(key, keyValues...) {
		api.h.NotFoundResponse(w, r)
		return
	}

	if !validator.Matches(bg, validator.ColorHex) {
		bg = "000000"
	}

	if !validator.Matches(fg, validator.ColorHex) {
		fg = "ffffff"
	}

	data := &templateData{
		BackgroundColor: bg,
		ForegroundColor: fg,
	}
	api.render(w, r, key + ".tmpl", data)
}

func (api *Api) htmlRoutes(router *httprouter.Router) {
	router.HandlerFunc(http.MethodGet, "/v1/html/page", api.pageProvider)
}

func (api *Api) loadTemplateCache() (map[string]*template.Template, error) {
	cache := map[string]*template.Template{}
	pageDir := filepath.Join(api.config.Path.HtmlPath(), "*.tmpl")
	pages, err := filepath.Glob(pageDir)
	if err != nil {
		return nil, err
	}

	for _, page := range pages {
		name := filepath.Base(page)
		ts, err :=template.New(name).ParseFiles(page)
		if err != nil {
			return nil, err
		}
		cache[name] = ts
	}

	return cache, nil
}

func (api *Api) render(w http.ResponseWriter, r *http.Request, name string, data *templateData) {
	ts, ok := api.templateCache[name]
	if !ok {
		err := fmt.Errorf("the template %s does not exist", name)
		api.h.ServerErrorResponse(w, r, err)
		return
	}

	buf := new(bytes.Buffer)
	err := ts.Execute(buf, data)
	if err != nil {
		api.h.ServerErrorResponse(w, r, err)
		return
	}

	w.Header().Set("Content-Type", "text/html")
	w.WriteHeader(http.StatusOK)
	w.Write(buf.Bytes())
}